package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

// 服务端程序

// Tag是结构体的元信息，可以在运行的时候通过反射的机制读取出来。Tag在结构体字段的后方定义，由一对反引号包裹起来
type FormData struct {
	APIVersion   string `json:"apiVersion"`
	Kind         string `json:"kind"`
	MetadataName string `json:"metadataName"`
	SpecField    string `json:"specField"`
}

func main() {

	http.HandleFunc("/submit", handleSubmit)
	http.Handle("/", http.FileServer(http.Dir("./frontend")))

	fmt.Println("Server is running on port 8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatalf("Could not start server: %s\n", err.Error())
	}
}

func handleSubmit(w http.ResponseWriter, r *http.Request) {

	// 如果请求方法不符合要求，直接返回
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}

	var formData FormData
	err := json.NewDecoder(r.Body).Decode(&formData)
	if err != nil {
		http.Error(w, "Failed to parse request body", http.StatusBadRequest)
		return
	}

	// convert struct to YAML
	crdContent := fmt.Sprintf(`apiVersion: %s
kind: %s
metadata:
	name: %s
spec:
	field: %s
`, formData.APIVersion, formData.Kind, formData.MetadataName, formData.SpecField)

	// write YAML to file
	err = ioutil.WriteFile("output.crd", []byte(crdContent), 0644)
	if err != nil {
		http.Error(w, "Failed to create CRD file", http.StatusInternalServerError)
		return
	}

	// Respond with success
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]bool{"success": true})
}
